<template>
  <div class="app-container">
    <!-- 添加或修改往来客户对话框 -->
    <el-dialog :title="title" v-loading="openLoading" v-model="open" fullscreen append-to-body>

      <el-descriptions class="margin-top" :column="userStore.isMobile ? 1 : 3"
        :direction="userStore.isMobile ? 'vertical' : 'horizontal'" border>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <user />
              </el-icon>
              发起人
            </div>
          </template>
          <el-tag size="large">{{ form?.promoterName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <user />
              </el-icon>
              往来客户
            </div>
          </template>
          <el-tag size="large">{{ form?.customerName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <user />
              </el-icon>
              销售负责人
            </div>
          </template>
          <el-tag size="large">{{ form?.saleName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <tickets />
              </el-icon>
              备注
            </div>
          </template>
          {{ form?.remark }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <iphone />
              </el-icon>
              出库起始日期
            </div>
          </template>
          {{ form?.startDate }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <location />
              </el-icon>
              出库截至日期
            </div>
          </template>
          {{ form?.endDate }}
        </el-descriptions-item>
      </el-descriptions>
      <el-row :style="{
        justifyContent: userStore.isMobile ? 'center' : 'space-around',
        flexDirection: userStore.isMobile ? 'column' : 'row'
      }" style="margin-bottom: 20px;margin-top: 20px;">
        <el-card
          :style="{ width: userStore.isMobile ? '80vw' : '15vw', marginBottom: userStore.isMobile ? '20px' : '0' }">
          <div
            style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
            <span style="padding-top: 10px;">
              销售总金额￥
              <el-tag size="large" type="primary">
                {{ form.total }}
              </el-tag>
            </span>
          </div>
        </el-card>

        <el-card
          :style="{ width: userStore.isMobile ? '80vw' : '15vw', marginBottom: userStore.isMobile ? '20px' : '0' }">
          <div
            style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
            <span style="padding-top: 10px;">
              成本合计￥：
              <el-tag size="large" type="primary">
                {{ form.costTotal }}
              </el-tag>
            </span>
          </div>
        </el-card>

        <el-card :style="{ width: userStore.isMobile ? '80vw' : '15vw' }">
          <div
            style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
            <span style="padding-top: 10px;">
              毛利润￥：
              <el-tag size="large" type="primary">
                {{ form.profit }}
              </el-tag>
            </span>
          </div>
        </el-card>

        <el-card :style="{ width: userStore.isMobile ? '80vw' : '15vw' }">
          <div
            style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
            <span style="padding-top: 10px;">
              管家婆实收金额￥：
              <el-tag size="large" type="primary">
                {{ actual }}
              </el-tag>
            </span>
          </div>
        </el-card>

        <el-card :style="{ width: userStore.isMobile ? '80vw' : '15vw' }">
          <div
            style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
            <span style="padding-top: 10px;">
              管家婆应收金额￥：
              <el-tag size="large" type="primary">
                {{ gjpShould }}
              </el-tag>
            </span>
          </div>
        </el-card>


      </el-row>


      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="出库信息" name="first">

          <el-input size="large" v-model="searchKeyword" placeholder="支持输入出库数量、设备全称、简称、型号、参数搜索" clearable :style="{
            width: userStore.isMobile ? '100%' : '400px',
            marginBottom: userStore.isMobile ? '10px' : '15px'
          }" :size="userStore.isMobile ? 'large' : 'default'" />

          <el-button style="margin-bottom: 15px;margin-left:  10px;" type="primary" plain
            @click="getSaleInfo(form, '2')">计算最新出库数据</el-button>

          <el-button style="margin-bottom: 15px;margin-left:  10px;" type="warning" plain icon="el-icon-download"
            size="mini" @click="handleExport">导出</el-button>

          <el-table v-loading="saleLoding" :max-height="50 + 'vh'" :row-class-name="tableRowClassName"
            style="overflow: auto;max-height: 50vh;" :summary-method="getSummaries" show-summary border
            element-loading-text="数据加载中..." :data="filteredSaleList">
            <el-table-column label="出库日期" align="center" prop="saleDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="设备型号" show-overflow-tooltip align="center" prop="modal" />

            <el-table-column label="数量" width="200" align="center" prop="amount" />
            <!-- <el-table-column label="成本单价" width="200" align="center" prop="costString" /> -->
            <el-table-column v-if="viewCost" label="成本单价" width="200" align="center">
              <template #default="scope">
                <div style="white-space: pre-line;">{{ scope.row.costString }}</div>
              </template>
            </el-table-column>
            <el-table-column v-if="viewCost" label="成本合计(￥)" align="center" show-overflow-tooltip width="120"
              prop="costTotal" />
            <el-table-column label="销售单价(￥)" align="center" show-overflow-tooltip width="120" prop="price" />
            <el-table-column label="销售总金额(￥)" show-overflow-tooltip width="120" align="center" prop="total" />
            <el-table-column v-if="viewCost" label="毛利(￥)" show-overflow-tooltip width="120" align="center"
              prop="profit" />
            <el-table-column v-if="viewCost" label="毛利率(%)" show-overflow-tooltip width="120" align="center"
              prop="profitRatio" />
            <el-table-column label="设备全称" show-overflow-tooltip align="center" prop="fullName" />
            <el-table-column label="设备简称" show-overflow-tooltip width="220" align="center" prop="name" />
            <el-table-column label="设备参数" show-overflow-tooltip align="center" prop="param" />
            <el-table-column label="管家婆项目" fixed="bottom" show-overflow-tooltip width="220" align="center"
              prop="companyName" />
          </el-table>

          <pagination v-show="total > 0" :total="totalSale" v-model:page="queryParamsSale.pageNum"
            v-model:limit="queryParamsSale.pageSize" @pagination="getListSale" />

        </el-tab-pane>

        <el-tab-pane label="核算信息" name="second">

          <el-button type="primary" plain :icon="Plus" v-if="accountingList.length == 0" @click="addProfit()"
            style="margin-bottom: 10px;">添加利润计算</el-button>

          <el-button type="primary" v-if="userStore.name == 'wuzg'" plain :icon="Plus" @click="issueMoney()"
            style="margin-bottom: 10px;margin-left: 10px;">绩效发放</el-button>

          <el-table :summary-method="getSummary" show-summary :row-class-name="tableRowClassNamePro" border
            v-loading="loading" :data="accountingList">
            <el-table-column label="类型" align="center" prop="type">
              <template #default="scope">
                <dict-tag :options="profit_type" :value="scope.row.type" />
              </template>
            </el-table-column>
            <el-table-column label="此类型的结算总额" align="center" width="100" prop="projectAmount" />
            <el-table-column label="项目税额" align="center" width="100" prop="taxAmount" />
            <el-table-column label="项目材料成本" align="center" width="100" prop="materialCost" />
            <el-table-column label="其他成本一(报销费用)" align="center" width="100" prop="costOne" />
            <el-table-column label="其他成本二" align="center" width="100" prop="costTwo" />
            <el-table-column label="其他成本三" align="center" width="100" prop="costThree" />
            <el-table-column label="资金成本" align="center" width="100" prop="fundCost" />
            <el-table-column label="外协人工成本" align="center" width="100" prop="laborCost" />
            <el-table-column label="税率(%)" align="center" prop="rate" />
            <el-table-column label="毛利润" align="center" width="100" prop="profit" />
            <el-table-column label="成本税费" align="center" width="100" prop="costFees" />
            <el-table-column label="差额税费" align="center" width="100" prop="differenceFees" />
            <el-table-column label="税前利润" align="center" width="100" prop="beforeProfit" />
            <el-table-column label="质保金" align="center" width="100" prop="retentionMoney" />
            <el-table-column label="纯利润扣质保金" align="center" width="100" prop="afterProfit" />
            <el-table-column label="项目提成" align="center" width="100" prop="projectCommission" />
            <el-table-column label="操作" align="center" fixed="right" :width="userStore.isMobile ? 80 : 220"
              class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" v-if="scope.row.audit == '4' && userStore.name == 'wuzg'"
                  @click="handleUpdateProfit(scope.row)">修改</el-button>
                <!-- <el-button link type="primary" v-if="scope.row.audit == '1' && userStore.name != 'wuzg'"
                  @click="handleUpdateProfit(scope.row)">修改</el-button> -->
                <el-button link type="primary" v-if="scope.row.audit == '4' && userStore.name == 'wuzg'"
                  @click="handleDeleteProfit(scope.row)">删除</el-button>
                <!-- <el-button link type="primary" v-if="scope.row.audit == '1'"
                  @click="submitInfo(scope.row, '提交', '2')">确认提交</el-button>
                <el-button link type="primary" v-if="scope.row.audit == '2' && userStore.name != 'wuzg'"
                  @click="submitInfo(scope.row, '撤销', '1')">撤销</el-button>
                <el-button link type="primary" v-if="scope.row.audit == '2' && userStore.name == 'wuzg'"
                  @click="submitInfo(scope.row, '通过审核', '4')">通过审核</el-button>
                <el-button link type="primary" v-if="scope.row.audit == '2' && userStore.name == 'wuzg'"
                  @click="submitInfo(scope.row, '驳回', '1')">驳回</el-button>
                <el-button link type="primary" v-if="scope.row.audit == '4' && userStore.name == 'wuzg'"
                  @click="submitInfo(scope.row, '驳回', '1')">驳回</el-button> -->
                <!-- <el-tooltip content="此操作会重新计算截至到目前的利润、成本、费用及提成等信息" placement="top">
                  <el-button v-if="scope.$index === 0 " link type="success"
                    @click="refreshCost(scope.row)"> 获取最新数据
                  </el-button>
                </el-tooltip> -->


                <el-tooltip content="此操作会重新计算截至到目前的利润、成本、费用及提成等信息" placement="top">
                  <el-button link type="success" @click="setNewInfo(scope.row)"> 获取最新数据
                  </el-button>
                </el-tooltip>

              </template>
            </el-table-column>
          </el-table>


          <el-divider style="font-size: 16px; font-weight: bold;">收款信息</el-divider>

          <el-row :gutter="10" style="display: flex; align-items: center;">
            <el-col :span="5">
              <el-tooltip content="调平金额" placement="top">
                <el-input type="number" @wheel.native.prevent v-model="form.subAmount" placeholder="请输入调平金额"
                  size="large" style="width: 100%;">
                  <template #prefix>
                    <el-icon>
                      <Money />
                    </el-icon>
                  </template>
                </el-input>
              </el-tooltip>
            </el-col>
            <el-col :span="2">
              <el-button type="success" size="large" @click="customerSubAmount(form)"
                style="width: 100%; font-weight: 500;">
                阶段应收调整
              </el-button>
            </el-col>

            <el-col :span="2">
              <el-button style="margin-bottom: 15px;margin:  10px;" type="warning" plain icon="el-icon-download"
                size="mini" @click="handleExportFee">导出</el-button>
            </el-col>
          </el-row>


          <el-table :key="tableKey" :summary-method="getPaySummary" show-summary border
            :row-class-name="tableRowClassNameConfig" :data="payList" style="margin-top: 20px;">


            <el-table-column label="销售总金额" align="center" show-overflow-tooltip prop="settlementAmount" />
            <el-table-column label="财务实收金额" align="center" show-overflow-tooltip prop="receivedAmount" />
            <el-table-column label="备注" show-overflow-tooltip align="center" prop="remark" />
            <el-table-column label="收/付日期" show-overflow-tooltip align="center" prop="payDate" />
            <el-table-column label="销售单总金额" align="center" show-overflow-tooltip prop="configTotal" />

            <el-table-column label="操作" fixed="right" align="center" width="320" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button v-if="scope.row.remark != '调平金额'" link type="primary" icon="Edit"
                  @click="openConfig(scope.row)">销售单配置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="绩效发放记录" name="three">
          <el-table v-loading="loading" :data="logList">
            <el-table-column label="序号" type="index" width="100" align="center" />
            <el-table-column label="销售负责人" align="center" prop="personName" />
            <el-table-column label="个人总绩效" align="center" prop="personTotalt" />
            <el-table-column label="个人本次发放" align="center" prop="personCurrent" />
            <el-table-column label="个人剩余" align="center" prop="personWait" />
            <el-table-column label="部门总绩效" align="center" prop="deptTotalt" />
            <el-table-column label="部门本次发放" align="center" prop="deptCurrent" />
            <el-table-column label="部门剩余" align="center" prop="deptWait" />
            <el-table-column label="发放时间" align="center" prop="startDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="利润计算信息" v-model="openProfit" :width="userStore.isMobile ? '95%' : '900px'" append-to-body>
      <el-form ref="accountingRef" size="large" :model="profitForm" :rules="profitRules" label-width="160px">
        <el-form-item label="类型" prop="type">
          <el-select @change="setTypeName" v-model="profitForm.type" placeholder="请选择类型">
            <el-option v-for="dict in profit_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="此类型的结算总额" prop="projectAmount">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.projectAmount" placeholder="请输入此类型的结算总额" />
        </el-form-item>


        <el-form-item label="项目材料成本" prop="materialCost">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.materialCost"
            placeholder="请输入项目材料成本" />
        </el-form-item>
        <el-form-item label="其他成本一(报销费用)" prop="costOne">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.costOne"
            placeholder="请输入其他成本一" />
        </el-form-item>
        <el-form-item label="其他成本二" prop="costTwo">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.costTwo" placeholder="请输入其他成本二" />
        </el-form-item>
        <el-form-item label="其他成本三" prop="costThree">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.costThree" placeholder="请输入其他成本三" />
        </el-form-item>

        <el-form-item label="质保金" prop="retentionMoney">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.retentionMoney" placeholder="请输入质保金" />
        </el-form-item>

        <el-form-item label="占用资金金额" prop="useAmount">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.useAmount" placeholder="" />
        </el-form-item>

        <el-form-item v-if="!userStore.isMobile">
          <el-tag size="small">提示：如有资金占用金额,需要输入资金使用时间以及月利率用于计算资金成本</el-tag>
        </el-form-item>


        <el-form-item label="资金使用时间(月)" prop="costTime">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.costTime" placeholder="资金使用时间" />
        </el-form-item>

        <el-form-item label="月利率" prop="monthRate">
          <el-input type="number" @wheel.native.prevent @blur="handleBlurFundCost()" v-model="profitForm.monthRate"
            placeholder="请输入月利率" />
        </el-form-item>

        <el-form-item label="资金成本" prop="fundCost">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.fundCost"
            placeholder="请输入资金成本" />
        </el-form-item>

        <el-form-item label="人工成本" prop="laborCost">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.laborCost" placeholder="请输入人工成本" />
        </el-form-item>
        <el-form-item label="税率(%)" prop="laborCost">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.rate" :disabled="true" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="profitForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitProfitForm">确 定</el-button>
          <el-button @click="cancelProfit">取 消</el-button>
        </div>
      </template>

    </el-dialog>

    <el-drawer @open="handleDrawerOpen" v-model="issueOpen" title="绩效发放" direction="btt" :with-header="false"
      size='40%'>

      <el-table v-loading="loading" border :data="customerList">
        <el-table-column label="往来客户名称" align="center" show-overflow-tooltip width="300" prop="customerName" />
        <el-table-column label="销售负责人" align="center" prop="saleName" />
        <el-table-column label="销售总金额" align="center" prop="total" />
        <el-table-column label="毛利" align="center" prop="profit" />
        <el-table-column label="个人绩效总金额" align="center" prop="personTotal" />
        <el-table-column label="个人绩效已发放" align="center" prop="personAlready" />
        <el-table-column label="个人待发放" align="center" prop="personWait" />
        <el-table-column label="个人本次发放" align="center" width="150">
          <template #default="scope">
            <el-input type="number" @wheel.native.prevent v-model="scope.row.personCurrent" placeholder=""></el-input>
          </template>
        </el-table-column>

        <el-table-column label="部门绩效总金额" align="center" prop="deptTotal" />
        <el-table-column label="部门绩效已发放" align="center" prop="deptAlready" />
        <el-table-column label="部门绩效待发放" align="center" prop="deptWait" />
        <el-table-column label="部门绩效本次发放" align="center" width="150">
          <template #default="scope">
            <el-input type="number" @wheel.native.prevent v-model="scope.row.deptCurrent" placeholder=""></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="issueClick(scope.row)">确认发放</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-collapse accordion>
        <el-collapse-item title="历史发放记录" name="1" @click="getLosList">
          <el-table v-loading="loading" :data="logList">
            <el-table-column label="序号" type="index" width="100" align="center" />
            <el-table-column label="销售负责人" align="center" prop="personName" />
            <el-table-column label="个人总绩效" align="center" prop="personTotalt" />
            <el-table-column label="个人本次发放" align="center" prop="personCurrent" />
            <el-table-column label="个人剩余" align="center" prop="personWait" />
            <el-table-column label="部门总绩效" align="center" prop="deptTotalt" />
            <el-table-column label="部门本次发放" align="center" prop="deptCurrent" />
            <el-table-column label="部门剩余" align="center" prop="deptWait" />
            <el-table-column label="发放时间" align="center" prop="startDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>

    </el-drawer>


    <el-drawer v-model="configView" title="销售单配置" :with-header="false" size='60%'>
      <el-input size="large" v-model="searchKeyword" placeholder="支持输入出库数量、设备全称、简称、型号、参数搜索" clearable :style="{
        width: userStore.isMobile ? '100%' : '400px',
        marginBottom: userStore.isMobile ? '10px' : '15px'
      }" :size="userStore.isMobile ? 'large' : 'default'" />

      <el-button style="margin-bottom: 15px;margin-left:  10px;" type="warning" plain icon="el-icon-download"
        size="mini" @click="saveConfig()">保存配置</el-button>

      <el-switch v-model="queryParams.showCheckedOnly" inline-prompt @change="handleShowTypeChange"
        style="--el-switch-on-color: #13ce66; margin-bottom: 10px;margin-left: 20px; --el-switch-off-color: #ff4949"
        active-text="已配置" inactive-text="全部" />

      <el-table :summary-method="getSummariesConfig" show-summary :row-key="getRowKey" ref="saleTableRef"
        v-loading="saleLoding" :max-height="80 + 'vh'" style="overflow: auto;max-height: 80vh;" border
        element-loading-text="数据加载中..." :data="saleConfigList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="出库日期" align="center" prop="saleDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备型号" show-overflow-tooltip align="center" prop="modal" />
        <el-table-column label="设备全称" width="200" show-overflow-tooltip align="center" prop="fullName" />
        <el-table-column label="数量" width="80" align="center" prop="amount" />
        <el-table-column label="销售总金额(￥)" show-overflow-tooltip width="120" align="center" prop="total" />
        <el-table-column label="设备参数" show-overflow-tooltip align="center" prop="param" />
      </el-table>

    </el-drawer>

  </div>
</template>

<script setup>
import { listCompany, listAccountingCustomer, getTotalCostByDate } from "@/api/project/project";
import { saleConfigInfo, getCustomer, delCustomer, addCustomer, updateCustomer, auditCustomer, listCustomerSale, updateSubAmount, updateIssueMoney } from "@/api/project/customer";
import { ElLoading } from 'element-plus'
import { viewCostPermisson } from "@/api/project/sale";
import { listAllUser, getUser, getPosts } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import { listFee, delFee, addFee, updateFee, totalFeeByDate, getReceiveAndPayForCustomer } from "@/api/project/fee";
import { listPay, listImplement, getTotalCost, getPay, delPay, addPay, updateIds, updatePay, listPhase, getPhase, delPhase, addPhase, updatePhase, listAccounting, updateNewInfo, getAccounting, delAccounting, addAccounting, updateAccounting, updateAudit } from "@/api/project/project";
import { listLog, getLog, delLog, addLog, updateLog } from "@/api/project/log";
import { addConfig, updateConfig, saveOrUpdateConfig, getConfigByFeeKey } from "@/api/project/config";


const { proxy } = getCurrentInstance();
const { profit_type } = proxy.useDict('profit_type');
const { rate_type } = proxy.useDict('rate_type');

const tableKey = ref(0);

// 需要“刷新”时调用
function refreshTable() {
  tableKey.value += 1; // 触发重新渲染
}

const payList = ref([])
const logList = ref([])

const accountingList = ref([]);
const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName

  if (activeName.value == 'second') {
    getCustomerFee()
    getAccountList()
  }

  if (activeName.value == 'three') {
    getLosList()
  }

}

const issueOpen = ref(false)

async function issueMoney() {

  //获取最新的利润计算
  let params = {
    mainId: currentId.value
  }
  await listAccountingCustomer(params).then((response) => {
    accountingList.value = response.data;

  });


  if (accountingList.value.length == 0) {
    proxy.$modal.msgError("请先添加利润计算信息");
    return
  }

  for (let index = 0; index < accountingList.value.length; index++) {
    const element = accountingList.value[index];
    console.log("审核audit", element);
    if (element.audit == '2') {//如果有待审核的 提示需要先审核通过
      proxy.$modal.msgError("有待审核的利润计算信息,请先审核通过后再进行绩效发放");
      return
    }
  }

  issueOpen.value = true

  //获取最新
  getCustomer(currentId.value).then(response => {
    // form.value = response.data;
    console.log("logggg", response.data);
    customerList.value = []
    customerList.value.push(response.data)
  })

  getLosList()

}


function issueClick(row) {
  console.log("发放", row);
  updateIssueMoney(row).then(response => {
    proxy.$modal.msgSuccess("提交成功");
    getCustomer(currentId.value).then(response => {
      // form.value = response.data;
      console.log("logggg", response.data);
      customerList.value = []
      customerList.value.push(response.data)
    })
  })

}


function getLosList() {
  let param = {
    detailId: form.value.id
  }
  listLog(param).then((response) => {
    logList.value = response.data;
  });
}



function afterEndDate() {
  const now = new Date(); // 当前时间
  const endDate = new Date(form.value.endDate); // 将 endDate 转为 Date 对象
  // 判断当前时间是否大于结束时间
  return now < endDate;
}

function getPaySummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'receivedAmount',
      'receivedPercentage',
      'promissoryNote'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}

function getCustomerFee() {
  let params = {
    mainId: currentId.value
  }
  getReceiveAndPayForCustomer(params).then((response) => {
    payList.value = response.data;
    refreshTable()
  });
}


/** 导出按钮操作 */
function handleExport() {

  let params = {
    id: currentId.value
  }

  proxy.download('project/accounting/export', {
    ...params
  }, `出库单数据_${new Date().getTime()}.xlsx`)


}


/** 导出按钮操作 */
function handleExportFee() {
  let params = {
    mainId: currentId.value
  }
  proxy.download('project/fee/exportFee', {
    ...params
  }, `收/付明细${new Date().getTime()}.xlsx`)

}


/** 修改付款信息按钮操作 */
async function handleUpdateProfit(row) {
  resetProfit();
  const _Id = row.id || ids.value

  await getAccounting(_Id).then(response => {
    profitForm.value = response.data;
    openProfit.value = true;
  });
}

function getSummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'projectAmount',
      'taxAmount',
      'materialCost',
      'costOne',
      'costTwo',
      'costThree',
      'fundCost',
      'laborCost',
      'profit',
      'costFees',
      'differenceFees',
      'beforeProfit',
      'retentionMoney',
      'afterProfit',
      'projectCommission'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}

function getSummaryLog(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'personTotalt',
      'personCurrent',
      'personWait',
      'deptTotalt',
      'deptCurrent',
      'deptWait',
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}


const materialCost = ref(-1)

const bxFee = ref(0)

const openProfit = ref(false);

//添加付款信息 销售负责人添加付款信息？
async function addProfit() {
  resetProfit();
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '成本费用计算中...' });
  // 定义定时任务
  let intervalId = null;

  //重新获取最新的
  materialCost.value = -1
  getSaleListPage(2)

  intervalId = setInterval(() => {
    // 检查 materialCost 是否不等于 -1
    if (materialCost.value != -1 && bxFee.value != undefined && bxFee.value != null) {
      // 关闭加载状态
      loadingInstance.close();
      // 清除定时任务
      clearInterval(intervalId);
      loadingInstance.close()
      console.log('加载状态已关闭');

      // profitForm.value.projectAmount = contractAmount.value//合同签订金额自动带出 取结算金额？
      profitForm.value.projectAmount = form.value.total
      profitForm.value.materialCost = materialCost.value

      //报销费用 材料费用 只能添加一次
      if (accountingList.value.length > 0) {
        profitForm.value.materialCost = 0
      } else {
        profitForm.value.materialCost = materialCost.value
      }

      profitForm.value.costOne = bxFee.value;
      // personList.value = []
      openProfit.value = true

    }
  }, 500); // 每隔 500ms 检查一次

  let param1 = {
    customerId: form.value.customerId,
    mainId: currentId.value,
    refresh: '1'
  }
  await totalFeeByDate(param1).then(response => {
    bxFee.value = response.data;
    console.log("总报销费用", bxFee.value);
  });

  //报销费用只取一次
  if (accountingList.value.length > 0) {
    bxFee.value = 0
    profitForm.value.costOne = bxFee.value;
  }


}

//重新获取报销费用
async function refreshCost(row) {
  resetProfit();
  const _Id = row.id || ids.value

  const loadingInstance = ElLoading.service({ fullscreen: true, text: '报销费用获取中...' });
  let param1 = {
    customerId: form.value.customerId,
    mainId: currentId.value,
    refresh: '1'
  }
  // if (accountingList.value.length == 0) {
  await totalFeeByDate(param1).then(response => {
    bxFee.value = response.data;
    console.log("总报销费用", bxFee.value);
  });

  getAccounting(_Id).then(response => {
    profitForm.value = response.data;
    profitForm.value.costOne = bxFee.value
    openProfit.value = true;
    loadingInstance.close()
  });
}


async function setNewInfo(row) {

  const loadingInstance = ElLoading.service({ fullscreen: true, text: '最新数据计算中...' });
  //1.先获取最新报销费用
  let param1 = {
    customerId: form.value.customerId,
    mainId: currentId.value,
    refresh: '1'
  }
  await totalFeeByDate(param1).then(response => {
    bxFee.value = response.data;
    console.log("总报销费用", bxFee.value);
  });
  row.costOne = bxFee.value

  //2.后端
  await updateNewInfo(row).then(response => {
    // getListParticipan(projectNo.value)
    getAccountList()
  });

  getCustomer(row.mainId).then(response => {
    form.value = response.data;
    subAmount.value = form.value.subAmount
  })

  loadingInstance.close()
  console.log("row", row);


}

// 取消按钮
function cancelProfit() {
  openProfit.value = false;
  resetProfit();
}

/** 删除付款信息按钮操作 */
function handleDeleteProfit(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delAccounting(_Id);
  }).then(() => {
    //getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
    getAccountList()
  }).catch(() => { });
}

//销售负责人提交核算的数据
function submitInfo(row, title, types) {
  profitForm.value = row
  proxy.$modal.confirm('是否确认' + title + '？').then(async function () {
    if (profitForm.value.id != null) {
      profitForm.value.audit = types
      console.log("提交的数据", profitForm.value);
      await updateAudit(profitForm.value).then(response => {
        proxy.$modal.msgSuccess(title + "成功");
      });
      let params = {
        mainId: currentId.value
      }
      listAccountingCustomer(params).then((response) => {
        accountingList.value = response.data;
      });

    }
  }).then(() => {

  }).catch(() => { });
}


function setTypeName(id) {
  //对应的名称
  const filteredObjects = profit_type.value.find(item => item.value == id);
  profitForm.value.typeName = filteredObjects.label
  const result = rate_type.value.find(item => item.label == profitForm.value.typeName);
  console.log("profitForm.value.typeName", profitForm.value.typeName);

  console.log("resultresult", filteredObjects.label, result);
  if (!result) {
    proxy.$modal.msgError("未找到此类型的税率信息，请联系管理员配置");
    return
  }
  profitForm.value.rate = result.value

  console.log("iddddd", id);

  if (accountingList.value.length > 0) {
    profitForm.value.materialCost = 0
  } else {
    profitForm.value.materialCost = materialCost.value
  }


}


// 表单重置
function resetProfit() {
  profitForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("accountingRef");

}

function getAccountList() {
  let params = {
    mainId: currentId.value
  }
  listAccountingCustomer(params).then((response) => {
    accountingList.value = response.data;
  });
}

/** 提交按钮 */
function submitProfitForm() {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '数据提交中...' });
  //标识往来客户
  profitForm.value.isCustomer = 'Y'

  proxy.$refs["accountingRef"].validate(valid => {
    if (valid) {
      console.log("fffff", profitForm.value);

      profitForm.value.projectNo = form.value.customerId
      profitForm.value.mainId = currentId
      profitForm.value.phaseId = 5
      if (profitForm.value.id != null) {
        updateAccounting(profitForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openProfit.value = false;
          // getListParticipan(projectNo.value)
          getAccountList()
          loadingInstance.close();
        });
      } else {
        addAccounting(profitForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openProfit.value = false;
          // getListParticipan(projectNo.value)
          getAccountList()
          loadingInstance.close();
        });
      }
    }
  });
}



//绩效总金额
const totalMoney = ref('')


const userStore = useUserStore()


const { audit_type } = proxy.useDict('audit_type');
const customerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const totalSale = ref(0);
const title = ref("");
const companyList = ref([]);
const loadingQuery = ref(false)
const drawer = ref(false)
const saleList = ref([]);
const data = reactive({
  profitForm: {

  },
  form: {},
  configForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: null,
    customerName: null,
    startDate: null,
    endDate: null,
    status: "2",
    promoterId: null,
    promoterName: null,
    auditId: null,
    auditName: null,
    costTotal: null,
    profit: null,
    profitRatio: null,
    refresh: "1",
    housekeeperProject: '',
    saleId: null,
    saleName: null,
    gjpShould: null
  },
  queryParamsSale: {
    pageNum: 1,
    pageSize: 10,
    customerId: null,
    customerName: null,
    startDate: null,
    endDate: null,
    status: "2",
    promoterId: null,
    promoterName: null,
    auditId: null,
    auditName: null,
    costTotal: null,
    profit: null,
    profitRatio: null,
    refresh: "1",
    housekeeperProject: '',
    saleName: '',
  },
});

const { queryParamsSale, queryParams, form, configForm, rules, profitForm } = toRefs(data);


const tableRowClassName = ({ row }) => {

  return row.status == "1" ? 'warning-row' : '';
};

const tableRowClassNameConfig = ({ row }) => {

  //1为实收金额小于销售总金额  2为实收金额大于销售总金额 3为相等
  if (row.currRow == "1") {
    return 'warning-row'
  }

  if (row.currRow == "2") {
    return 'success-row'
  }

  if (row.currRow == "3") {
    return 'gray2-row'
  }



};




const tableRowClassNamePro = ({ row }) => {
  return row.rowStatus == "1" ? 'success-row' : '';
};




const userList = ref([])

const subAmount = ref(0)



onMounted(() => {
  listAllUser().then((response) => {
    userList.value = response
  });
});



function selectCompany(query) {
  console.log("queryquery", query);
  loadingQuery.value = true
  let params = {
    companyName: query
  }
  listCompany(params).then((response) => {
    companyList.value = response.data
    loadingQuery.value = false
  });
}

const searchKeyword = ref('');


// 计算属性过滤数据
const filteredSaleList = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  if (!keyword) {
    return saleList.value;
  }

  let x = saleList.value.filter(item =>
    [item.fullName, item.name, item.modal, item.param, item.amount].some(field =>
      field != null && String(field).toLowerCase().includes(keyword)
    )
  );


  return saleList.value.filter(item =>
    [item.fullName, item.name, item.modal, item.param, item.amount].some(field =>
      field != null && String(field).toLowerCase().includes(keyword)
    )
  );

});



function getSummaries(param) {
  const { columns, data } = param
  let filteredData = data.filter(item => item.name !== '已开增票');
  const sums = []
  columns.forEach((column, index) => {

    if (index === 0) {
      sums[index] = `合计（共 ${data.length} 条）`;
      return
    }

    const prop = column.property

    // 需要统计的列及其格式化方式
    const statsConfig = {
      amount: { format: 'int' },    // 数量列显示整数
      costTotal: { format: 'float' }, // 成本合计保留2位小数
      total: { format: 'float' },    // 销售总金额保留2位小数
      profit: { format: 'float' }    // 毛利保留2位小数
    }

    if (statsConfig[prop]) {
      const values = filteredData.map(item => Number(item[prop]))
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)

        // 根据配置格式化结果
        sums[index] = statsConfig[prop].format === 'int'
          ? Math.round(sum)
          : sum.toFixed(2)

        sums[index] = sums[index]


      } else {
        sums[index] = 'N/A'
      }
    } else {
      sums[index] = ''
    }
  })

  return sums
}

function getSummariesConfig(param) {
  const { columns, data } = param
  let filteredData = data.filter(item => item.name !== '已开增票');
  const sums = []
  columns.forEach((column, index) => {

    if (index === 1) {
      sums[index] = `合计（共 ${data.length} 条）`;
      return
    }

    const prop = column.property

    // 需要统计的列及其格式化方式
    const statsConfig = {
      costTotal: { format: 'float' }, // 成本合计保留2位小数
      total: { format: 'float' },    // 销售总金额保留2位小数
      profit: { format: 'float' }    // 毛利保留2位小数
    }

    if (statsConfig[prop]) {
      const values = filteredData.map(item => Number(item[prop]))
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)

        // 根据配置格式化结果
        sums[index] = statsConfig[prop].format === 'int'
          ? Math.round(sum)
          : sum.toFixed(2)

        sums[index] = sums[index]


      } else {
        sums[index] = 'N/A'
      }
    } else {
      sums[index] = ''
    }
  })

  return sums
}


function getListSale() {
  loading.value = true;
  getSaleListPage()
}

//管家婆应收
const gjpShould = ref('')
//管家婆实收
const actual = ref('')
//



// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    customerId: null,
    customerName: null,
    startDate: null,
    endDate: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    status: null,
    promoterId: null,
    promoterName: null,
    auditId: null,
    auditName: null,
    costTotal: null,
    profit: null,
    profitRatio: null,
    saleId: null,
    saleName: null
  };
  proxy.resetForm("customerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selectionRows) {


  console.log("selectionRows", selectionRows);

  // 生成联合主键字符串数组
  const selectedKeys = selectionRows.map(row =>
    `${row.goodsId}|${row.saleDate}|${row.amount}|${row.housekeeperProject}|${row.price}`
  );


  // 存储联合主键字符串数组（替代原来的 ids）
  ids.value = selectedKeys;

  // 调试
  console.log("联合主键字符串数组:", ids.value);
}

const selectedRowIds = ref(new Set());

const saleTableRef = ref()

const configView = ref(false)

const currentRow = ref()

async function openConfig(row) {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '数据查询中...' });
  currentRow.value = row
  configForm.value = {
  }

  console.log("openrowwww", row);

  configForm.value.feeKey = ''
  console.log("ppppp", configForm.value);
  const totalStr = Number(row.total).toFixed(2); // 确保是数字再转
  const feeKey = `${row.housekeeperProject}|${totalStr}|${row.useType}|${row.mainType}|${row.submitDate}`
  configForm.value.feeKey = feeKey
  console.log("feeKey", feeKey);

  //查询已绑定未绑定
  form.value.excludeFeeKey = ''
  form.value.excludeFeeKey = feeKey
  const response = await saleConfigInfo(form.value);

  //保存原始列表到缓存
  originalSaleConfigList.value = response.data.saleList;

  saleConfigList.value = response.data.saleList;

  const datas = await getConfigByFeeKey(feeKey);

  console.log("datassssss", datas);

  ids.value = datas.data?.saleKey


  // 假设 datas.data.saleKey 是联合主键字符串数组，例如 ["id1|date1|...", ...]
  // const selectedKeys = datas.data.saleKey || [];
  const selectedKeySet = new Set(datas.data?.saleKey || []);


  // 1. 先清空当前选中（可选）
  saleTableRef.value?.clearSelection();

  // 2. 根据 selectedKeys 在 saleConfigList 中查找对应的 row 对象

  const rowsToSelect = saleConfigList.value.filter(item => {
    const itemKey = `${item.goodsId}|${item.saleDate}|${item.amount}|${item.housekeeperProject}|${item.price}`;
    return selectedKeySet.has(itemKey); // ⚡ 快速查找
  });

  // 3. 更新 ids.value 为联合主键（用于后续保存等）
  ids.value = selectedKeySet;

  // ✅ 重点：初始化选中状态（避免打开弹窗时选中状态丢失）
  selectedKeys.value = [];

  // ... [后面代码不变] ...

  // 修改：用 selectedKeys 代替 ids.value 做选中逻辑
  // ids.value = datas.data?.saleKey || [];

  // 用 selectedKeys 保存初始选中（和 ids.value 无关！）
  selectedKeys.value = ids.value; // 初始选中状态

  // 4. 在 nextTick 中选中这些行

  nextTick(() => {
    let index = 0;
    const batchSize = 50; // 每帧处理 50 条

    const processBatch = () => {
      const end = Math.min(index + batchSize, rowsToSelect.length);
      for (; index < end; index++) {
        saleTableRef.value?.toggleRowSelection(rowsToSelect[index], true);
      }
      if (index < rowsToSelect.length) {
        requestAnimationFrame(processBatch);
      }
    };

    requestAnimationFrame(processBatch);
  });

  loadingInstance.close()
  //查询已绑定的
  configView.value = true

}

const originalSaleConfigList = ref([]); // 专门存原始数据

const selectedKeys = ref([]); // 专门存当前选中的键（不是 ids.value！）

function handleShowTypeChange(type) {
  console.log("切换", type);

  // ✅ 1. 切换前：保存当前选中的键（必须！）
  const currentSelectedKeys = [...selectedKeys.value]; // 深拷贝

  if (type) {
    // 已绑定：过滤 saleConfigList
    saleConfigList.value = saleConfigList.value.filter(item => {
      const itemKey = `${item.goodsId}|${item.saleDate}|${item.amount}|${item.housekeeperProject}|${item.price}`;
      return ids.value.includes(itemKey); // 用 ids.value 过滤（已绑定的）
    });
  } else {
    // 全部：恢复原始列表
    saleConfigList.value = originalSaleConfigList.value;
  }

  // ✅ 2. 切换后：用之前保存的键重新选中
  nextTick(() => {
    if (saleTableRef.value) {
      saleTableRef.value.clearSelection(); // 先清空

      // 遍历之前保存的选中键
      currentSelectedKeys.forEach(key => {
        const row = saleConfigList.value.find(item => {
          const itemKey = `${item.goodsId}|${item.saleDate}|${item.amount}|${item.housekeeperProject}|${item.price}`;
          return itemKey === key;
        });

        if (row) {
          saleTableRef.value.toggleRowSelection(row, true);
        }
      });

      // ✅ 3. 更新 selectedKeys（保证下次切换能正确保存状态）
      selectedKeys.value = currentSelectedKeys.filter(key =>
        saleConfigList.value.some(item => {
          const itemKey = `${item.goodsId}|${item.saleDate}|${item.amount}|${item.housekeeperProject}|${item.price}`;
          return itemKey === key;
        })
      );
    }
  });
}



async function saveConfig() {
  configForm.value.saleKey = ids.value
  console.log("666", configForm.value);
  await saveOrUpdateConfig(configForm.value).then(response => {
    proxy.$modal.msgSuccess("提交成功");
    openConfig(currentRow.value)
  });
  getCustomerFee()



}

// 绝对安全版（推荐用于生产环境）
const getRowKey = (row) =>
  JSON.stringify([row.goodsId, row.saleDate, row.amount, row.housekeeperProject, row.price]);

const saleConfigList = ref([])

async function getSaleConfig() {
  const response = await saleConfigInfo(form.value);
  saleConfigList.value = response.data.saleList;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加往来客户";
}


const currentId = ref()

function customerSubAmount(row) {
  let param = {
    subAmount: form.value.subAmount,
    id: row.id
  }

  updateSubAmount(param).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    getCustomerFee();
    getCustomer(currentId.value)

    getCustomer(row.id).then(response => {

      form.value = response.data;
      subAmount.value = form.value.subAmount
      console.log("xxxxxx", actual.value, form.value.subAmount);

      actual.value = parseFloat((actual.value - subAmount.value).toFixed(2));


    });

  });

}

/** 修改按钮操作 */
//打开弹框
const openLoading = ref(false)
function handleUpdate(row) {

  activeName.value = 'first'
  currentId.value = row.id
  getAccountList()
  getCustomer(row.id).then(response => {

    form.value = response.data;
    subAmount.value = form.value.subAmount

    console.log("rrrrrr", form.value);

    if (form.value.customerName) {
      selectCompany(form.value.customerName)
    }
    open.value = true;
    title.value = "详细信息";

    getSaleListPage()

  });
}


function getSaleInfo(row, types) {
  queryParams.value.refresh = types
  queryParams.value.id = row.id
  getCustomer(row.id).then(response => {
    form.value = response.data;
    if (form.value.customerName) {
      selectCompany(form.value.customerName)
    }
    open.value = true;
    title.value = "详细信息";

    getSaleListPage(types)

  });
}


const saleLoding = ref(false)

function getSaleListPage(types) {
  saleLoding.value = true
  queryParamsSale.value.housekeeperProject = form.value.customerId
  queryParamsSale.value.startDate = form.value.startDate
  queryParamsSale.value.endDate = form.value.endDate
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '数据查询中...' });
  form.value.refresh = types
  listCustomerSale(form.value).then(response => {
    console.log("出库单数据", response);
    saleList.value = response.data.saleList;
    form.value = response.data.projectCustom

    materialCost.value = form.value.costTotal

    gjpShould.value = response.data.gjpShould
    // actual.value = response.data.actual - form.value.subAmount
    actual.value = parseFloat((response.data.actual - subAmount.value).toFixed(2));

  }).finally(() => {
    saleLoding.value = false
    loading.value = false;
    loadingInstance.close();
  });

  getSaleConfig()

}
const viewCost = ref(false)
function getViewCostPermisson() {
  viewCostPermisson(null).then(response => {
    console.log("看成本的权限", response);
    viewCost.value = response
  }).finally(() => {
  });
}

onMounted(() => {
  getViewCostPermisson()

})

defineExpose({ handleUpdate });
</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .gray2-row {
  --el-table-tr-bg-color: #fab1bb;
}
</style>